package com.thoughtworks.yuyijq.generate.element;

import org.apache.commons.lang.builder.ToStringBuilder;

/**
 * User: yuyijq
 * Date: Oct 10, 2010
 * Time: 10:15:24 AM
 */
public class ImportElement implements MemberElement {
    private String importStatement;

    public int read(String source) {
        importStatement = source.substring(0,source.indexOf(';')+1);
        return importStatement.length();
    }

    public String getImportStatement() {
        if(importStatement.startsWith("import")){
            importStatement = importStatement.substring("import".length());
        }
        if(hasClassPartial(importStatement)){
            importStatement = importStatement.substring(0,importStatement.lastIndexOf('.'));
        }
        if(importStatement.endsWith(";")){
            importStatement = importStatement.substring(0,importStatement.length()-1);
        }
        return importStatement.trim();
    }

    private boolean hasClassPartial(String importStatement) {
        for(int i = 0;i < importStatement.length();++i){
            if(Character.isUpperCase(importStatement.charAt(i))){
                return true;
            }
        }
        return false;
    }

    @Override
    public String toString() {
        return new ToStringBuilder(this).
                append("importStatement", importStatement).
                toString();
    }
}
